package com.skyline.energy.provider.spring;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.SqlParameterValue;
import org.springframework.jdbc.core.SqlTypeValue;
import org.springframework.jdbc.core.StatementCreatorUtils;

public final class BatchPreparedStatementSetterCreator {
	private BatchPreparedStatementSetterCreator() {
		
	}
	
	public static BatchPreparedStatementSetter createBatchPreparedStatementSetter(final List<Object[]> argsList) {
		BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() {

			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				Object[] args = argsList.get(i);
				if (args != null) {
					for (int index = 0; index < args.length; index++) {
						Object arg = args[index];
						if (arg instanceof SqlParameterValue) {
							SqlParameterValue paramValue = (SqlParameterValue) arg;
							StatementCreatorUtils.setParameterValue(ps, index + 1, paramValue, paramValue.getValue());
						} else {
							StatementCreatorUtils.setParameterValue(ps, index + 1, SqlTypeValue.TYPE_UNKNOWN, arg);
						}
					}
				}
			}

			@Override
			public int getBatchSize() {
				return argsList.size();
			}
		};

		return setter;
	}
}
